// 两数相加
// https://leetcode-cn.com/problems/add-two-numbers/
// 给定两个非空链表，表示两个非负整数，它们每位都是按照逆序的方式存储的，并且每个节点只存储一位数字。
// 请你将两数相加，并以相同形式返回一个表示和的链表

import { ListNode, array2list } from '../utils/index.ts';

function addTwoNumbers(
    l1: ListNode | null,
    l2: ListNode | null
): ListNode | null {
    let carry = 0;
    let head: ListNode | null = null;
    let tail: ListNode | null = null;

    while (l1 || l2) {
        const n1 = l1 ? l1.val : 0;
        const n2 = l2 ? l2.val : 0;
        const sum = n1 + n2 + carry;
        carry = Math.floor(sum / 10);
        const v = sum % 10;

        if (!head) {
            head = tail = new ListNode(v);
        } else if (tail) {
            tail.next = new ListNode(v);
            tail = tail.next;
        }

        if (l1) {
            l1 = l1.next;
        }

        if (l2) {
            l2 = l2.next;
        }
    }

    if (carry && tail) {
        tail.next = new ListNode(1);
    }

    return head;
}

const l1 = array2list([1, 2, 3]);
const l2 = array2list([4, 5, 6]);
console.log(addTwoNumbers(l1, l2));
